import axios from "axios"
import type { AxiosInstance, AxiosRequestConfig } from "axios"
import { IXTinterceptors, IXTAxiosconfig } from "./ceptors-interface"
import { ElLoading } from "element-plus"

class XtRequest {
  instance: AxiosInstance
  interceptors: IXTinterceptors
  loadingInstance: any
  constructor(config: IXTAxiosconfig) {
    this.instance = axios.create(config)
    this.interceptors = config.interceptors

    //请求拦截器
    this.instance.interceptors.request.use(
      config.interceptors.requestSuccess,
      config.interceptors.requestFail,
    )

    //响应拦截器
    this.instance.interceptors.response.use(
      config.interceptors.responseSuccess,
      config.interceptors.responseFail,
    )

    // 全局请求拦截器
    this.instance.interceptors.request.use((config) => {
      // 开启loading
      this.loadingInstance = ElLoading.service({
        lock: true,
        text: "正在加载...",
        background: "rgba(0,0,0,.5)",
      })
      return config
    })

    // 全局响应拦截器
    this.instance.interceptors.response.use(
      (res) => {
        // 关闭loading
        this.loadingInstance.close()

        return res
      },
      (err) => {
        // 关闭loading
        this.loadingInstance.close()
        return err
      },
    )
  }

  request<T>(config: AxiosRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      this.instance(config)
        .then((res) => {
            resolve(res?.data)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  get<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: "GET" })
  }

  post<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: "POST" })
  }

  delete<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: "DELETE" })
  }

  patch<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: "PATCH" })
  }
}

export default XtRequest
